import React, { Component } from "react";
import {
  View,
  Text,
  TextInput,
  TouchableOpacity,
  DeviceEventEmitter
} from "react-native";
import NavBarConfig from "../modules/NavBar";
import Base64 from "../../util/base64";
import {
  TRANSFER_CREDIT,
  TRANSFER_BGT,
  MEMBER_BGT,
  MEMBER,
  WALLET,
  COUNTRY,
  TRANSFER_CODE
} from "../../config/Api";
import http from "../../util/http";
import { toast } from "../../util/tip";
import TelSelect from "../modules/TelSelect";
import transferStyles from "../../style/pages/transferAndSettle";
import inviteStyles from "../../style/pages/InviteFriend";
import redeemStyles from "../../style/pages/redeem";
import { Color } from "../../style/common";
import { UNSET_PASSWORD } from "../../util/Const";
import { getTimer } from "../../util/util";

class Transfer extends Component {
  static navigationOptions = ({ navigation }) =>
    NavBarConfig(
      {
        headerTitle: "劃轉",
        headerRight: []
      },
      navigation
    );
  state = {
    selfAddress: null,
    bgt: 0,
    credit: 0,
    type: 0,
    verifyMsg: "獲取驗證碼",
    isCodeRequesting: false,

    amountInput: "",
    addressInput: "",
    passwordInput: "",
    code: "",
    countries: [],
    countryCode: "86",
    addressType: 1,
    paramTel: null,
    paramAddress: null,

    inTransferRequesting: false
  };

  async getCountries() {
    const data = await http.get(COUNTRY);
    this.setState({
      countries: data.data
    });
  }

  handleChangeType(addressType = 1) {
    if (addressType == 1 && this.state.paramTel) {
      this.setState({
        addressInput: this.state.paramTel
      });
    }
    if (addressType != 1 && this.state.paramAddress) {
      this.setState({
        addressInput: this.state.paramAddress
      });
    }
    this.setState({ addressType });
  }

  async getMemberInfo() {
    const data = await http.get(MEMBER);
    this.setState({
      tel: data.data.tel
    });
  }

  async getBgtAmount() {
    const wallet = await http.get(WALLET);
    const bgt = await http.get(MEMBER_BGT);
    this.setState({
      bgt: bgt.data.amount,
      credit: bgt.data.credit,
      selfAddress: wallet.data.address
    });
  }
  /**
   * @description∏
   * @author xiezuobing[948466]<435321508@qq.com>
   * @param {*} country
   * @memberof Transfer
   */
  handleCodeChange(country) {
    this.setState({
      contryCode: country.code
    });
  }

  initQueryInfo() {
    if (!this.props.navigation.state.params) return;
    this.setState({
      type: parseInt(this.props.navigation.state.params.type) || 0,
      amountInput: this.props.navigation.state.params.amount,
      addressInput: this.props.navigation.state.params.tel,
      paramTel: this.props.navigation.state.params.tel,
      paramAddress: this.props.navigation.state.params.address
    });
  }

  changeType(type = 0) {
    this.setState({
      type: type
    });
  }

  componentWillMount() {
    this.getMemberInfo();
    this.getBgtAmount();
    this.getCountries();
    this.subscription = DeviceEventEmitter.addListener(UNSET_PASSWORD, () => {
      this.props.navigation.navigate("SetTradePassword");
    });
  }

  componentWillUnmount() {
    this.subscription.remove();
  }

  componentDidMount() {
    this.initQueryInfo();
  }

  handleChange(key, text) {
    let data = {};
    data[key] = text;
    this.setState({
      ...data
    });
  }

  async gotoTransfer() {
    if (this.state.inTransferRequesting) return;
    let target = this.state.addressInput.trim();
    if (this.state.addressType == 1) target = this.state.countryCode + target;
    const password = this.state.passwordInput.trim();
    const amount = Number(this.state.amountInput.trim());
    const code = this.state.code.trim();

    if (!amount) {
      toast("請填寫有效金額");
      return;
    }

    if (amount % 1 != 0) {
      toast("轉出額度必須為整數");
      return;
    }

    if (!target) {
      if (this.state.addressType == 1) {
        toast("請填寫正確的手機號");
      } else {
        toast("請填寫正確的錢包地址");
      }
      return;
    }

    if (!password) {
      toast("請填寫正確的支付密碼");
      return;
    }

    if (!code) {
      toast("請填寫正確的驗證碼");
      return;
    }
    await this.setState({
      inTransferRequesting: true
    });

    try {
      const data = await http.post(
        this.state.type == 0
          ? TRANSFER_CREDIT + "/" + target
          : TRANSFER_BGT + "/" + target,
        {
          target: target,
          password: Base64.encode(password),
          amount: amount,
          code: code
        }
      );
      if (data) {
        toast("劃轉成功");
        this.props.navigation.goBack();
      }
    } catch (e) {
      alert(e.message);
    }
    this.setState({
      inTransferRequesting: false
    });
  }

  async handleSendCode() {
    if (this.state.isCodeRequesting) return;
    const value = this.state.tel;
    if (!value) {
      return;
    }

    this.setState({
      isCodeRequesting: true
    });
    const data = await http.post(TRANSFER_CODE, {
      tel: value
    });
    if (data) {
      getTimer(
        50,
        time => {
          this.setState({
            verifyMsg: `${time}s`
          });
        },
        () => {
          this.setState({
            verifyMsg: "獲取驗證碼"
          });
        }
      );
    }
    this.setState({
      isCodeRequesting: false
    });
  }

  render() {
    return (
      <View>
        <View style={transferStyles.settlementTab}>
          <TouchableOpacity
            style={transferStyles.settlementItem}
            onPress={() => this.changeType(0)}
          >
            <Text
              style={[
                transferStyles.item,
                this.state.type == 0 ? transferStyles.itemActive : {}
              ]}
            >
              轉出額度
            </Text>
            <View
              style={
                this.state.type == 0 ? transferStyles.itemActiveBottom : {}
              }
            />
          </TouchableOpacity>
          <TouchableOpacity
            style={transferStyles.settlementItem}
            onPress={() => this.changeType(1)}
          >
            <Text
              style={[
                transferStyles.item,
                this.state.type == 1 ? transferStyles.itemActive : {}
              ]}
            >
              轉出BGT
            </Text>
            <View
              style={
                this.state.type == 1 ? transferStyles.itemActiveBottom : {}
              }
            />
          </TouchableOpacity>
        </View>

        <View style={transferStyles.settlementItemContainer}>
          <Text style={transferStyles.settlementLeftOrRight}>轉出額度</Text>
          <TextInput
            underlineColorAndroid="transparent"
            keyboardType="numeric"
            style={transferStyles.input}
            placeholder={
              this.state.type == 0
                ? "最多可劃轉" + this.state.credit
                : "最多可劃轉" + this.state.bgt
            }
            value={this.state.amountInput}
            onChangeText={text => this.handleChange("amountInput", text)}
          />
          <Text style={transferStyles.settlementLeftOrRight}>
            {/* <a>全部</a> */}
          </Text>
        </View>
        <View style={transferStyles.settlementItemContainer}>
          <Text style={transferStyles.settlementLeftOrRight}>轉給用户</Text>
          <View
            style={[
              transferStyles.input,
              { flexDirection: "row", alignItems: "center" }
            ]}
          >
            <View style={transferStyles.addressTypeSelect}>
              <TouchableOpacity
                style={[
                  transferStyles.addressTypeSelectItem,
                  { borderRightColor: "#f2f2f2", borderRightWidth: 1 },
                  this.state.addressType == 1 ? { display: "none" } : {}
                ]}
                onPress={() => this.handleChangeType(1)}
              >
                <Text style={{ color: "#adc3d2" }}>切换为用户手机号</Text>
              </TouchableOpacity>
              <TouchableOpacity
                style={[
                  transferStyles.addressTypeSelectItem,
                  this.state.addressType == 2 ? { display: "none" } : {}
                ]}
                onPress={() => this.handleChangeType(2)}
              >
                <Text
                  style={{
                    color: "#adc3d2"
                  }}
                >
                  切换为BGT地址
                </Text>
              </TouchableOpacity>
            </View>
          </View>
        </View>
        {this.state.addressType == 1 ? (
          <View style={inviteStyles.inviteFriendWrap}>
            <View>
              <TelSelect
                data={this.state.countries}
                onSelect={this.handleCodeChange.bind(this)}
              />
            </View>
            <TextInput
              underlineColorAndroid="transparent"
              style={inviteStyles.input}
              placeholder="請輸入手機號碼"
              value={this.state.addressInput}
              onChangeText={text => this.handleChange("addressInput", text)}
            />
          </View>
        ) : null}
        {this.state.addressType == 2 ? (
          <View style={transferStyles.settlementItemContainer}>
            <Text
              style={[
                transferStyles.settlementLeftOrRight,
                { color: "rgba(0,0,0,0)" }
              ]}
            >
              占位字符
            </Text>
            <TextInput
              underlineColorAndroid="transparent"
              style={transferStyles.input}
              placeholder="BGT钱包地址"
              value={this.state.addressInput}
              onChangeText={text => this.handleChange("addressInput", text)}
            />
          </View>
        ) : null}

        <View
          style={[
            transferStyles.settlementItemContainer,
            { alignItems: "center" }
          ]}
        >
          <Text style={transferStyles.settlementLeftOrRight}>驗證碼</Text>
          <TextInput
            underlineColorAndroid="transparent"
            placeholder="請輸入獲取驗證碼"
            style={[redeemStyles.input, transferStyles.input]}
            onChangeText={text => this.handleChange("code", text)}
          />
          <TouchableOpacity
            onPress={this.handleSendCode.bind(this)}
            disabled={
              this.state.isCodeRequesting ||
              !this.state.tel ||
              this.state.verifyMsg !== "獲取驗證碼"
            }
          >
            <Text
              style={[
                redeemStyles.button,
                {
                  backgroundColor:
                    this.state.isCodeRequesting ||
                    !this.state.tel ||
                    this.state.verifyMsg !== "獲取驗證碼"
                      ? "gray"
                      : Color
                }
              ]}
            >
              {this.state.verifyMsg}
            </Text>
          </TouchableOpacity>
        </View>
        <View style={transferStyles.settlementItemContainer}>
          <Text style={transferStyles.settlementLeftOrRight}>支付密碼</Text>
          <TextInput
            underlineColorAndroid="transparent"
            password={true}
            secureTextEntry={true}
            style={transferStyles.input}
            placeholder="請輸入支付密碼"
            onChangeText={text => this.handleChange("passwordInput", text)}
          />
        </View>

        <View style={transferStyles.tranferTip}>
          <TouchableOpacity
            onPress={() => this.props.navigation.navigate("Receiptcode")}
            style={{
              flex: 1
            }}
          >
            <Text style={transferStyles.tranferText}>向我劃轉</Text>
          </TouchableOpacity>
          <Text style={[transferStyles.tranferSpan]}>
            可轉
            {this.state.type == 0 ? "数量" : "BGT数"}:
            {this.state.type == 0 ? this.state.credit : this.state.bgt}
          </Text>
        </View>

        <TouchableOpacity onPress={this.gotoTransfer.bind(this)}>
          <Text style={transferStyles.settlementConfirm}>確定</Text>
        </TouchableOpacity>
      </View>
    );
  }
}

export default Transfer;
